<?php

class Application_Model_RegisterUser
{
    /**
     * Instanz der Zend_Db_Table_Abstract User
     * @var Zend_Db_Table_Abstract 
     */
    protected $_dbModel;
    
    /**
     * Instanz eines Zend_Form Objektes
     * @var Zend_Form 
     */
    protected $_form;
    
    /**
     * Array bestehend aus der Formulareingabe
     * @var array 
     */
    protected $_formData;
    
    /**
     * Enthält die Datenbank Elemente als Array die bereits vergeben sind.
     * @var array 
     */
    protected $_errors = array();
    
    public function __construct(Array $formData, Zend_Form $formOb) 
    {
        $this->_dbModel  = new Application_Model_DbTable_User();
        $this->_form     = $formOb;
        $this->_formData = $formData;
    }
    
    /**
     * Prüft ob die Übergebenen Daten korrekt sind.
     * @return boolean 
     */
    public function check()
    {
        if($this->_form->isValid($this->_formData)) {
            $this->_formData = $this->_form->getValidValues($this->_formData);
            return TRUE;
        } else {
            return FALSE;
        }
    } 
    
    
    public function isDataValid()
    {
        $dbAdapter = $this->_dbModel->getAdapter();
        
        $where = 'name = ' . $dbAdapter->quote($this->_formData['name'])
               . ' OR '
               . 'email = ' . $dbAdapter->quote($this->_formData['email']);
        
        $rowSet = $this->_dbModel->fetchAll($where);
        
        if(count($rowSet) >= 1) {
            foreach ($rowSet as $row) {
                if($row['name'] == $this->_formData['name']) {
                    $this->_errors[] = 'Name <b>' . $row['name'] . '</b> ist schon vergeben.';
                }
                
                if($row['email'] == $this->_formData['email']) {
                    $this->_errors[] = 'Email <b>' . $row['email'] . '</b> ist schon vergeben.';
                }
            }
        } else {
            return;
        }      
    }
    
    /**
     * Liefert, wenn Daten doppel sind, ein Array der doppelten Daten zurück.
     * Ansonsten NULL
     * @return Array/NULL 
     */
    public function getErrors()
    {
        if(count($this->_errors) >= 0) {
            return $this->_errors;
        } else {
            return null;
        }
    }


    public function saveData()
    {
        unset($this->_formData['pw2']);
        $this->_formData['pw'] = md5($this->_formData['pw']);
        $uId = $this->_dbModel->insert($this->_formData);
    }
}

